package homework.service;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import homework.database.Util;

public class InitListener implements ServletContextListener {
	
	public InitListener() {
		
	}
	
	private void initDatabase() {
		
		Util.execute("create table user(id integer primary key auto_increment, "
				+ "account varchar(128) not null, "
				+ "password varchar(128) not null, "
				+ "name varchar(128) not null) default charset=utf8", 
				Util.emptySqlArgs(), (st) -> st.execute());
		
		Util.execute("insert into user(account, password, name) values(?, ?, ?)", 
				Util.asSqlArgs("admin", "123456", "Admin"), 
				(st) -> st.execute());
	}

	private String getWebInfPath() {
		
		String path = new File(InitListener.class.getResource("").getFile()).getAbsolutePath();
	
		return path.substring(0, path.indexOf("WEB-INF") + 8);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {

	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		try {
			if(new File(getWebInfPath() + "init.lock").createNewFile()) {
				System.out.println("初始化数据库 ... ");
				initDatabase();
				System.out.println("数据库初始化完毕 ... ");
			} else {
				System.out.println("数据库存在，跳过初始化阶段 ... ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
